#!/bin/bash
set -euo pipefail
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
source ${SCRIPT_DIR}/common

# Expect base collection path as an argument
BASE_COLLECTION_PATH=$1
NAMESPACE=${2:-openshift-logging}

log "BEGIN <gather_cluster_logging_operator_resources> from namespace: $NAMESPACE ..."

# Use PWD as base path if no argument is passed
if [ "${BASE_COLLECTION_PATH}" = "" ]; then
    BASE_COLLECTION_PATH=$(pwd)
fi

CLO_COLLECTION_PATH="$BASE_COLLECTION_PATH/cluster-logging"
# Adding namespace folders to allow for multi-logging
clo_folder="$CLO_COLLECTION_PATH/clo"

log "Creating namespace directory: $clo_folder"
mkdir -p "$clo_folder"

# We only need these from the openshift-logging namespace
if [ $NAMESPACE == "openshift-logging" ]; then
  log "Gathering data for 'cluster-logging-operator' from namespace: $NAMESPACE"

  pods=$(oc -n $NAMESPACE get pods -l name=cluster-logging-operator -o jsonpath='{.items[*].metadata.name}')
  for pod in $pods
  do
      log "Inspecting $pod"
      get_env $pod $clo_folder $NAMESPACE "Dockerfile-.*operator*"
  done
fi

log "Gathering 'version' from logging namespace: $NAMESPACE"
csv_name="$(oc -n $NAMESPACE get csv -o name | grep -E 'cluster(-?)logging')"
oc -n $NAMESPACE get "${csv_name}" -o jsonpath='{.spec.displayName}{"/must-gather\n"}{.spec.version}' --cache-dir=${KUBECACHEDIR} > "${clo_folder}/version"

log "END <gather_cluster_logging_operator_resources> from namespace: $NAMESPACE ..."
